﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web.Mvc;

namespace CommonApp
{
    public static class NotificationHelper
    {
        public static void AddNotification(this ViewDataDictionary viewData, string message, string type)
        {
            if (viewData == null)
                throw new ArgumentNullException("viewData");

            if (viewData[InfoKey.Notifications] == null)
                viewData[InfoKey.Notifications] = new List<dynamic>();

            var notifications = (List<dynamic>)viewData[InfoKey.Notifications];

            dynamic notification = new ExpandoObject();
            notification.message = message;
            notification.type = type;
            notifications.Add(notification);
        }

        public static void AddNotification(this TempDataDictionary tempData, string message, string type)
        {
            if (tempData == null)
                throw new ArgumentNullException("tempData");

            if (tempData[InfoKey.Notifications] == null)
                tempData[InfoKey.Notifications] = new List<dynamic>();

            var notifications = (List<dynamic>)tempData[InfoKey.Notifications];

            dynamic notification = new ExpandoObject();
            notification.message = message;
            notification.type = type;
            notifications.Add(notification);
        }

        public static IEnumerable<dynamic> Notifications(this WebViewPage view)
        {
            var viewDataNotifications = (IEnumerable<dynamic>)view.ViewData[InfoKey.Notifications] ?? Enumerable.Empty<dynamic>();
            var tempDataNotifications = (IEnumerable<dynamic>)view.TempData[InfoKey.Notifications] ?? Enumerable.Empty<dynamic>();
            view.TempData[InfoKey.Notifications] = null;
            return viewDataNotifications.Concat(tempDataNotifications);
        }
    }
}
